<template>
  <div class="user-look">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账号设置">
          <el-form
            ref="form"
            class="form"
            label-width="100px"
            :rules="rules"
            :model="form"
          >
            <el-form-item label="姓名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码" show-password prop="password">
              <el-input v-model="form.password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit">更新</el-button>
              <el-button @click="cancelClick">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情">
          <info :user-info="infoData" lazy @changeHtmel="changeHtmel" />
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <job />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
// 导入获取用户的api
import { sysUser, sysUserPut } from '@/api/user'

export default {
  components: {
    info: () => import('./components/info.vue'), // 组件懒加载
    job: () => import('./components/job.vue') // 组件懒加载
  },
  data() {
    return {
      userId: this.$route.params.id,
      rules: {
        username: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        password: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            min: 6,
            max: 12,
            message: '请输入6-12位数密码',
            trigger: 'change'
          }
        ]
      },
      form: {
        username: '',
        password: ''
      },
      userInfo: {},
      infoData: {}
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 根据id获取员工数据
    async getData() {
      const res = await sysUser(this.userId)
      this.userInfo = res.data
      this.form.username = res.data.username
      // 账号设置点击更新是 用户信息修改的内容双向绑定 导致其他信息被修改
      this.infoData = JSON.parse(JSON.stringify(res.data))
    },
    // 点击确定进行全局表单验证
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          await sysUserPut({ ...this.userInfo, ...this.form })

          // 点击更新是 用户信息的内容需要更新
          this.infoData.username = this.form.username
          this.infoData.password = this.form.password
          this.$message.success('修改用户信息成功')
        }
      })
    },
    // 取消
    cancelClick() {
      this.$router.push('/employees')
    },
    // 子组件更新 父组件也更新
    changeHtmel(obj) {
      this.userInfo = JSON.parse(JSON.stringify(obj))
      this.form.username = obj.username
    }
  }
}
</script>

<style lang="scss" scoped>
.user-look {
  padding: 15px;
  .form {
    width: 600px;
    padding: 50px;
    margin: 0 auto;
  }
}
</style>
